import glo
from machine import UART,Pin, SPI,Timer
import utime
import IMU
from OLED import *
from NETWORK import *

glo._init()#先必须在主模块初始化（只在Main模块需要一次即可）
#定义跨模块全局变量
# buf_list = []
# glo.set_value('buf_list',buf_list)

'''
    停用了buf方案，因为高低频刷新总有闪烁的现象，很影响观感，暂时没想到该怎么解决
'''
status = 0
lock = 0
IMU_data = {'ACC_Z':-1}
snt = 0
snt_lock = 0
def tim_irq(key):
    global IMU_data
    global status
    global snt
    global snt_lock
    global lock
    
    if IMU.judge_frame(uart1):
        IMU_data = IMU.dataSolving(uart1.read(9))
        if IMU_data['ACC_Z'] <0.8 and lock == 0:
            snt += 1
        else:
            snt = 0
        if snt >= 7 :
            status += 1
            snt = 0
            lock = 1
            oled.fill(0)
        # 解锁条件
        if IMU_data['ACC_Z'] >0.9 and lock == 1:
            snt_lock += 1
        if snt_lock >= 7:
            lock = 0
            snt_lock = 0
    if status >=3:
        status = 0
        oled.fill(0)
#         oled.fill(0)
#     if status % 2 == 1:
#         oled.fill(0)
#     oled.fill(0)
#     for i in buf_list:
#         oled.blit(i[0], i[1], i[2])
#     oled.show()
#     buf_list = []
 
    
# 可以重定向引脚
uart1 = UART(2, baudrate=115200, tx=17, rx=16)
# 进行水平校准
IMU.order_send(IMU.order_list['correct_order'],uart1)
# # 设置为加速度输出
# IMU.order_send(IMU.order_list['acc_output'],uart1)
# # 保存设置
# IMU.order_send(IMU.order_list['save_order'],uart1)
network = NETWORK('EHOME_7E9D','18503451399')
glo.set_value('network',network)
utime.sleep_ms(150)



# while True:
#     print(IMU_data['ACC_Z'])
#     utime.sleep_ms(100)
# oled = OLED_init()
# OLED_fonts((16,16),weather_fonts,(5,0),0,oled)
oled = OLED_init()
# glo.set_value('oled',oled)
tim0 = Timer(0)
tim0.init(period=20,mode=Timer.PERIODIC,callback=tim_irq)
dicc = {'0':screen1,
        '1':screen2,
        '2':screen3}
# bias = 0
while True:
    t = status
#     if t % 2 == 0:
    dicc[str(t)](oled,(0,0),0)
        
#     else:
# #         oled.fill(0)
#         dicc[str(t-1)](oled,(0,0),bias,buf_list)
#         dicc[str(t+1)](oled,(128,0),bias,buf_list)
# #         bias -= 4
#         
#     if bias == -128:
#         bias = 0
#         status += 1
#         oled.fill(0)
    
    
#     print(f'status:{status},ACC_Z:{IMU_data['ACC_Z']},  {snt}')
#     print(IMU_data['ACC_Z'])